<?php
include_once '/var/www/html/new/d/class/Sale.class.php';
include_once '/var/www/html/new/d/module/api/function.class.php';

class Meituan{
	
	private $mt_mid = 28227;// 分销商ID 美团  定死
	private $inside = null;
		
	public function __construct(){
		$this->inside = new SoapClient(null,array(
			"location" => "http://localhost/open/openService/pft_insideMX.php",
			"uri" => "www.16u.com?ac_16u=16ucom|pw_16u=c33367701511b4f6020ec61ded352059|auth_16u=true"));
		$this->outside  = new SoapClient("http://open.12301.cc/openService/MXSE.wsdl",array('encoding' =>'UTF-8','cache_wsdl' => 0));
	}
	
	//抓取POI景区信息
	public function catch_poi_product($partnerId,$partnerPoiId,$totalSize){
		$response = $this->response_header($partnerId,$totalSize);
		$pic = strpos($product['imgpath'], "images.12301.cc/");
		if($pic !== false)	$urls = array($product['imgpath'],);
		else	$urls = array('http://www.12301.cc/'.$product['imgpath'],);
		foreach($partnerPoiId as $lid){
			$sel = "select title,address,tel,bhjq,jqts,lng_lat_pos,imgpath,area from uu_land where id=".$lid." limit 1";
			$GLOBALS['le']->query($sel);
			$info = $GLOBALS['le']->fetch_assoc();
			$jwd = explode(",",$info['lng_lat_pos']);
			$area = explode("|",$info['area']);
			
			$selarea  = "select area_name from uu_area where area_id=".$area[0]." limit 1";
			$GLOBALS['le']->query($selarea);
			
			$area = $GLOBALS['le']->fetch_assoc();
			$body = array(
				'partnerId'=>$partnerId,
				'partnerPoiId'=>$lid,
				'name'=>$info['title'],
				'address'=>$info['address'],
				'city'=>$area['area_name'],
				'phone'=>$info['tel'],
				'description'=>$info['jqts'],
				'longitude'=>$jwd[0] * pow(10,6),
				'latitude'=>$jwd[1]* pow(10,6),
				'img'=>array(
					'urls' =>$urls,
					),
				'imgText'=>$info['bhjq'],
			);		
			$response['body'][] = $body;
		}
		// exit(json_encode($response));
		return json_encode($response);
	}
		
	//预约订单
	public function PFT_OrderValidate($params){
		$ids =  explode("|",$params['body']['partnerDealId']);//票付通组合ID
		$aid = $ids[0]; //供应商id
		$lid = $ids[1]; //景区id
		$tid = $ids[2]; //门票id
		$fid = $this->mt_mid; 
		
		if(!$tid)  exit('{"code":300,"describe":"请求数据有误"}');
		// 获取PID
		$sqlpid = "select pid from uu_jq_ticket where id=$tid limit 1";
		$GLOBALS['le']->query($sqlpid);
		if(!($rowpid=$GLOBALS['le']->fetch_assoc()))  {
			$response = array(
				'code' => 300, 
				'describe' => '不存在分销商',
				'partnerId' => $params['partnerId'],
				'body' => array( 
					'orderStatus' => 1, 
				),
			);
			exit(json_encode($response));
		}
		$pid = $rowpid['pid'];
		
		// 获取分销商信息
		$sql = "select account,dname from pft_member where id=$fid limit 1";
		$GLOBALS['le']->query($sql);
		if(!($d_info=$GLOBALS['le']->fetch_assoc()))  {
			$response = array(
				'code' => 300, 
				'describe' => '不存在分销商',
				'partnerId' => $params['partnerId'],
				'body' => array( 
					'orderStatus' => 1, 
				),
			);
			exit(json_encode($response));
		}
		
		// 获取产品数据
		$sql = "select p.id as pid,p.apply_limit,p.salerid,p.p_status,p.apply_did,l.id as lid,l.title as ltitle,l.p_type,t.id as tid,";
		$sql.= "t.tprice,t.pay,t.title as ttitle,t.delaydays,t.ddays,t.buy_limit_low,t.buy_limit_up,t.status,t.storage_open,";
		$sql.= "t.storage,t.getaddr,f.dhour,f.series_model,f.mdays,f.v_ID_support from uu_products p left join uu_jq_ticket t on p.id=t.pid ";
		$sql.= "left join uu_land l on p.contact_id=l.id left join uu_land_f f on p.id=f.pid where p.id=$pid limit 1";
		$GLOBALS['le']->query($sql);
		$p_info = $GLOBALS['le']->fetch_assoc();

		// 是否在售
		if($p_info['apply_limit']!=1)  {
			$response = array(
				'code' => 300, 
				'describe' => '产品未审核或审核未通过',
				'partnerId' => $params['partnerId'],
				'body' => array( 
					'orderStatus' => 1, 
				),
			);
			exit(json_encode($response));
		}
        
        // 是否有购买权限
        $auth = self::authCheck($fid,$aid,$p_info);
        if(!$auth['auth']) {
			$response = array(
				'code' => 300, 
				'describe' => '无权限购买此产品',
				'partnerId' => $params['partnerId'],
				'body' => array( 
					'orderStatus' => 1, 
				),
			);
			exit(json_encode($response));
		}
        
        // 检测套票子票
        if($p_info['p_type']=='F'){
            $chkResult = \pft\Prod\Sale::PackageTicketCheck($this->inside, $pid, $fid, $aid, substr($valid_start, 0, 10), $num);
            if($chkResult['code']!=200)	exit('{"code":300,"describe":"子票出错，出错信息:'.$chkResult['msg'].'"}');
        }
        
        // 价格获取
        $begintime = $params['body']['visitDate'];
		$tnum      = $params['body']['quantity'];
		$sellPrice  = $params['body']['sellPrice'];	
		$ordername  = $params['body']['firstVisitor']['name'];
		$ordertel  = $params['body']['firstVisitor']['mobile'];	
		
		$xml2 = $this->inside->Dynamic_Price_And_Storage($d_info['account'],$pid,$begintime,1,1,1,$aid); //零售价
		if($xml2==105 || $xml2==1065) {
			$response = array(
				'code' => 300, 
				'describe' => '出游时间无价格，出游时间',
				'partnerId' => $params['partnerId'],
				'body' => array( 
					'orderStatus' => 1, 
				),
			);
			exit(json_encode($response));
		}
		$obj2 = simplexml_load_string($xml2);
        $jprice = (float)$obj2->Rec->UUsprice / 100;
		if($sellPrice != $jprice){
			$response = array(
				'code' => 300, 
				'describe' => '销售价格错误',
				'partnerId' => $params['partnerId'],
				'body' => array( 
					'orderStatus' => 1, 
				),
			);
			exit(json_encode($response));
		}
     
        $xml = $this->inside->Dynamic_Price_And_Storage($d_info['account'],$pid,$begintime,1,0,1,$aid); //结算价
		if($xml==105 || $xml==1065) {
			$response = array(
				'code' => 300, 
				'describe' => '出游时间无价格，出游时间',
				'partnerId' => $params['partnerId'],
				'body' => array( 
					'orderStatus' => 1, 
				),
			);
			exit(json_encode($response));
		}
        
        // 库存判断
		$obj = simplexml_load_string($xml);
        $storage = (string)$obj->Rec->UUstorage;
        $UUsprice = (float)$obj->Rec->UUsprice / 100;		

        if($storage>-1){
			$storagexml = $this->inside->Dynamic_Storage_Check($p_info['tid'], 1, $begintime);
			$storagexml = simplexml_load_string($storagexml);
			$dayStorage = explode("|", (string)$storagexml->Rec->UUXstr);
			$useStorage = $dayStorage[1];// 已使用库存
			$surplus    = $storage - $useStorage;// 剩余库存
			if($surplus<$tnum){
				$response = array(
					'code' => 300, 
					'describe' => '库存不足',
					'partnerId' => $params['partnerId'],
					'body' => array( 
						'orderStatus' => 1, 
					),
				);
				exit(json_encode($response));
			}
        }
		
        // 订单金额
		$tprice = (string)$obj->Rec->UUsprice;
		$totalMoney = $tprice*$tnum;
        
		$paymodel = 2;// 授信余额
		$fundXml=$this->inside->PFT_Member_Fund($fid,1,$aid);
		$fundXml1=simplexml_load_string($fundXml);
		
		$fundXml=$this->inside->PFT_Member_Fund($fid,2,$aid);
		$fundXml2=simplexml_load_string($fundXml);
		$canUseMoney = (string)$fundXml1->Rec->UUkmoney + (string)$fundXml2->Rec->UUbasecredit;
		if(($canUseMoney)<$totalMoney){
			$response = array(
				'code' => 300, 
				'describe' => '授信余额不足',
				'partnerId' => $params['partnerId'],
				'body' => array( 
					'orderStatus' => 1, 
				),
			);
			exit(json_encode($response));
		}
        		
		$response = array(
			'code' => 200, 
			'describe' => '预约成功',
			'partnerId' => $params['partnerId'],
			'body' => array( 
				'orderStatus' => 0, 
			),
		);
		exit(json_encode($response));
	}
	
	// 创建订单
	public function PFT_Order_Submit($params){
		$ids =  explode("|",$params['body']['partnerDealId']);//票付通组合ID
		$aid = $ids[0]; //供应商id
		$lid = $ids[1]; //景区id
		$tid = $ids[2]; //门票id
		$fid = $this->mt_mid; 
		
		if(!$tid)  exit('{"code":300,"describe":"请求数据有误"}');
		
		// 获取PID
		$sqlpid = "select pid from uu_jq_ticket where id=$tid limit 1";
		$GLOBALS['le']->query($sqlpid);
		if(!($rowpid=$GLOBALS['le']->fetch_assoc())) exit('{"code":300,"describe":"不存在分销商"}');
		$pid = $rowpid['pid'];
		
		// 获取分销商信息
		$sql = "select account,dname from pft_member where id=$fid limit 1";
		$GLOBALS['le']->query($sql);
		if(!($d_info=$GLOBALS['le']->fetch_assoc())) exit('{"code":300,"describe":"不存在分销商"}');
		
		// 获取产品数据
		$sql = "select p.id as pid,p.apply_limit,p.salerid,p.p_status,p.apply_did,l.id as lid,l.title as ltitle,l.p_type,t.id as tid,";
		$sql.= "t.tprice,t.pay,t.title as ttitle,t.delaydays,t.ddays,t.buy_limit_low,t.buy_limit_up,t.status,t.storage_open,";
		$sql.= "t.storage,t.getaddr,f.dhour,f.series_model,f.mdays,f.v_ID_support from uu_products p left join uu_jq_ticket t on p.id=t.pid ";
		$sql.= "left join uu_land l on p.contact_id=l.id left join uu_land_f f on p.id=f.pid where p.id=$pid limit 1";
		$GLOBALS['le']->query($sql);
		$p_info = $GLOBALS['le']->fetch_assoc();

		// 是否在售
		if($p_info['apply_limit']!=1) exit('{"code":300,"describe":"产品未审核或审核未通过:'.$pid.'"}');
		
		// 是否有购买权限
		$auth = self::authCheck($fid,$aid,$p_info);
		if(!$auth['auth']) exit('{"code":300,"describe":"无权限购买,产品ID:'.$pid.'"}');
		
		// 检测套票子票
		if($p_info['p_type']=='F'){
			$chkResult = \pft\Prod\Sale::PackageTicketCheck($this->inside, $pid, $fid, $aid, substr($valid_start, 0, 10), $num);
			if($chkResult['code']!=200)	exit('{"code":300,"describe":"子票出错，出错信息:'.$chkResult['msg'].'"}');
		}
		
		// 价格获取
		$begintime = $params['body']['visitDate'];
		$tnum      = $params['body']['quantity'];
		$ordername  = $params['body']['firstVisitor']['name'];
		$ordertel  = $params['body']['firstVisitor']['mobile'];
		
		// if($begintime != date('Y-m-d'))exit('{"code":300,"describe":"出行时间不是当天，需要下预约订单:'.$begintime.'"}');
		
		$xml = $this->inside->Dynamic_Price_And_Storage($d_info['account'],$pid,$begintime,1,0,1,$aid);
		if($xml==105 || $xml==1065) exit('{"code":300,"describe":"出游时间无价格，出游时间:'.$begintime.'"}');
		
		// 库存判断
		$obj = simplexml_load_string($xml);
		$storage = $obj->Rec->UUstorage;

		if($storage>-1){
			$storagexml = $this->inside->Dynamic_Storage_Check($p_info['tid'], 1, $begintime);
			$storagexml = simplexml_load_string($storagexml);
			$dayStorage = explode("|", (string)$storagexml->Rec->UUXstr);
			$useStorage = $dayStorage[1];// 已使用库存
			$surplus    = $storage - $useStorage;// 剩余库存
			if($surplus<$tnum) exit('{"code":300,"describe":"库存不足,剩余库存:'.$surplus.',需求:'.$tnum.'"}');
		}
		
		// 订单金额
		$tprice = (string)$obj->Rec->UUsprice;
		$totalMoney = $tprice*$tnum;
		
		$paymodel = 2;// 授信余额
		$fundXml=$this->inside->PFT_Member_Fund($fid,1,$aid);
		$fundXml1=simplexml_load_string($fundXml);
		
		$fundXml=$this->inside->PFT_Member_Fund($fid,2,$aid);
		$fundXml2=simplexml_load_string($fundXml);
		$canUseMoney = (string)$fundXml1->Rec->UUkmoney + (string)$fundXml2->Rec->UUbasecredit;
		if(($canUseMoney)<$totalMoney) exit('{"code":300,"describe":"授信余额不足"}');
				
		//创建订单成功
		$response = array(
			'code' => 200, 'describe' => '创建订单成功', 'partnerId' => $params['partnerId'],
			'body' => array( 'partnerOrderId' =>'', 'orderStatus' => 2, 'voucherType' =>0, 'voucher' =>''),
		);	
		exit(json_encode($response));		
	}
	
	//支付订单
	public function PFT_Order_Pay($params){
		$ids =  explode("|",$params['body']['partnerDealId']);//票付通组合ID
		$aid = $ids[0]; //供应商id
		$lid = $ids[1]; //景区id
		$tid = $ids[2]; //门票id
		$fid = $this->mt_mid; 
				
		if(!$tid)  exit('{"code":300,"describe":"请求数据有误"}');
		
		// 外部接口
		$account = '505270';
		$pw = '54a3fdb31cad4ef63cac2d9cc82cf784'; // 票付通账号跟密码
		$paymodel = 2;
		$submit_array = array(
			"ac"   => $account,           // 账号
			"pw"   => $pw,           // 密码
			"in0"  => $lid, // 景区id
			"in1"  => $tid, // 门票id
			"in2"  => $params['body']['bookOrderId'],// 远端订单号
			"in3"  => $params['body']['sellPrice'],        // 门票价格
			"in4"  => $params['body']['quantity'],          // 数量
			"in5"  => $params['body']['visitDate'],     // 游玩日期
			"in6"  => $params['body']['firstVisitor']['name'],  // 客户姓名
			"in7"  => $params['body']['firstVisitor']['mobile'],// 客户手机号
			"in8"  => '', // 联系人手机号
			"in9"  => 0,  // 是否发送短信（0发送1不发送）
			"in10" => $paymodel,// 扣款方式 0 账户余额 2 供应商处余额 4 现场支付
			"in11" => 0,   // 下单方式 0 正常 1 手机用户
			"in12" => "",  // 集合地点
			"in13" => "",  // 团号
			"in14" => 0,   // 联票ID
			"in15" => 0,   // 套票ID
			"in16" => $aid,// 供应商id
			"in17" => $params['body']['firstVisitor']['credentials']// 身份证
		);
		$simxml = $this->outside->__soapCall("PFT_Order_Submit",$submit_array);	
		// 返回数据 
		$simxml = simplexml_load_string($simxml);
		if((string)$simxml->Rec->UUordernum){
			$this->logfile((string)$simxml->Rec->UUordernum.'|'.$params['body']['bookOrderId'],"creatorder_success");
			$PFT_infunction = new AllFunction();
			$select = $PFT_infunction->Select_PFTorder((string)$simxml->Rec->UUordernum);
			if((string)$simxml->Rec->UUvcode!=0) $UUcode = (string)$simxml->Rec->UUvcode;
			else $UUcode = (string)$select->Rec->UUcode;
			$response = array(
				'code' => 200, 
				'describe' => "支付成功", 
				'partnerId' => $params['partnerId'],
				'body' => array( 
					'partnerOrderId' => (string)$simxml->Rec->UUordernum, 
					'orderStatus' => 4,
					'voucherType'=>0,
					'voucher'=>$UUcode
					)
				);
		}
		else{
			$this->logfile($params['body']['bookOrderId']."|".(int)$simxml->Rec->UUerrorcode,"creatorder_fail");
			$response = array(
				'code' => 300, 
				'describe' => (int)$simxml->Rec->UUerrorcode, 
				'partnerId' => $params['partnerId'],
				'body' => array( 
					'partnerOrderId' => 0, 
					'orderStatus' => 5
				)
			);
		}		
		exit(json_encode($response));
	}
		
	// 购买权限认证 分销商ID 上级供应ID 产品ID
	public static function authCheck($fid,$aid,$p_info){
		$arr = array('self'=>false,'auth'=>false);
		$pid = $p_info['pid'];
		if($p_info['apply_did']==$fid){ // 自供应
			$arr['self'] = true;
			$arr['auth'] = true;
			return $arr;
		}
		if($p_info['apply_did']==$aid){ // 直接供应
			$sql="select pids from `pft_product_sale_list` where fid=$fid and aid=$aid LIMIT 1";
			$GLOBALS['le']->query($sql);
			$GLOBALS['le']->fetch_assoc();
			$pids=$GLOBALS['le']->f("pids");
			if($pids=='A') $arr['auth'] = true;
			if(in_array($pid,explode(",",$pids)))$arr['auth'] = true;
			return $arr;
		}
		// 多手供应
		$sql="select * from pft_p_apply_evolute where pid=$pid and sid=$aid and fid=$fid and status=0 limit 1";
		$GLOBALS['le']->query($sql);
		if($row=$GLOBALS['le']->fetch_assoc())$arr['auth'] = true;
		return $arr;
	}
		
	// 获取账号可销售产品信息
	public function catch_product_information($partnerId,$partnerDealIds,$totalSize){
		$sid = 28227; //美团的会员id
		$account = 505270; //美团的账号
		$pids_arr = array();
		$prods = array();
		$response = $this->response_header($partnerId,$totalSize);
		
		$today = date('Y-m-d');
		
		foreach($partnerDealIds as $k){

			$tids =  explode("|",$k);
			$aid = $tids[0];
			$lid = $tids[1];
			$tid = $tids[2];
			
			$sel_pid = "select pid from uu_jq_ticket where id=$tid limit 1";
			$GLOBALS['le']->query($sel_pid);
			$GLOBALS['le']->fetch_assoc();
			$pid = $GLOBALS['le']->f('pid');
			
			$sql = "select p.id as pid,p.apply_did,t.landid,t.title as ttitle,t.id as tid,l.title as ltitle,l.salerid,l.area,l.topic,l.px,l.runtime,l.imgpath,l.address,t.id as tid,t.getaddr,t.title as ttitle,t.tprice,t.notes,	t.buy_limit_low,t.ddays,t.delaydays,t.status,f.ass_station,f.tourist_info,f.mdays,f.mhour,f.rdays,t.delaytype,t.ddays,t.buy_limit_up,t.buy_limit_low,p.verify_time,l.jqts,l.bhjq from uu_products p left join uu_jq_ticket t on t.pid=p.id left join uu_land l on l.id=t.landid left join uu_land_f f on f.pid=p.id where p.apply_limit=1 and p.p_status in (0,2,3,4,5) and t.pay=1 and p.apply_did<>$sid and p.id=$pid limit 1";
			$GLOBALS['le']->query($sql);
			$p_info = $GLOBALS['le']->fetch_assoc();
			if(!$p_info) continue;

			$fid = $this->mt_mid;
			$auth = self::authCheck($fid,$aid,$p_info);
			if(!$auth['auth']) continue;
			 
			$pStorage = $this->inside->Dynamic_Price_And_Storage($account, $p_info['pid'], $today,1,1,1,$aid);
			if($pStorage == 105 || $pStorage == 1065) continue;
			$pStorage = simplexml_load_string($pStorage);
			$p_info['ls']    = (string)$pStorage->Rec->UUsprice / 100;
			$p_info['stock'] = (string)$pStorage->Rec->UUstorage;
			if((int)$pStorage->Rec->UUstorage==-1) $p_info['stock'] = 100000000;// 库存不限传给定值

			$response['body'][] = $this->response_format_data($partnerId, $p_info, $k, $aid);
		}
		// print_r($response);exit;
		// exit(json_encode($response));		
		return json_encode($response);		
	}
	
	//产品变化通知
	public function PFT_ProductChangeNotice($ids,$status){
		$sql = "select supplierIdentity from uu_qunar_use where tid_aid='$ids' and DockingMode=1 limit 1";
		$GLOBALS['le']->query($sql);
		if($GLOBALS['le']->fetch_assoc()){
			$body = array(
				'partnerDealId'=>$ids,
				'status'=>$status
			);
			$response = array(
				'code'=>200,
				'describe'=>'产品变化通知',
				'partnerId'=>$GLOBALS['le']->f('supplierIdentity'),
				'body'=>$body				
			);	
			$changeurl = 'http://lvyou.meituan.com/rhone/lv/deal/change/notice';
			$this->RefundNotice($response,$changeurl);
		}
		exit;
	}
	
	// 取消订单
	public function PFT_order_Cancel($params){
		$ordernum = $params['body']['partnerOrderId'];
		$simxml = $this->inside->Order_Globle_Search("","","","","","","","","","","","",$ordernum,"","","","","",1,1,0,1,0,0,"",0,"","","","","");
		$simxml = simplexml_load_string($simxml);
		// $aid = (int)$simxml->Rec->UUaid;
		if(!isset($simxml->Rec)) exit('{"code":300,"describe":"订单不存在","partnerId":"'.$params['partnerId'].'"}');
		if((int)$simxml->Rec->UUmid != $this->mt_mid) 
			exit('{"code":300,"describe":"非接口订单","partnerId":"'.$params['partnerId'].'"}');
		if((int)$simxml->Rec->UUstatus==3) exit('{"code":300,"describe":"订单已取消","partnerId":"'.$params['partnerId'].'"}');
		if((int)$simxml->Rec->UUstatus==2) exit('{"code":300,"describe":"订单已过期","partnerId":"'.$params['partnerId'].'"}');
		if((int)$simxml->Rec->UUstatus==1) exit('{"code":300,"describe":"订单已使用","partnerId":"'.$params['partnerId'].'"}');
		
		if($params['body']['refundQuantity'] == (int)$simxml->Rec->UUtnum) $cancelnum = 0;
		elseif($params['body']['refundQuantity'] > (int)$simxml->Rec->UUtnum)	exit('{"code":300,"describe":"退款数量超过当前订单数量","partnerId":"'.$params['partnerId'].'"}');
		else $cancelnum = $params['body']['refundQuantity'];
		// 取消订单
		$rs = $this->inside->Order_Change_Pro($ordernum,$cancelnum,0,0,0);
		if($rs ==100){
			$this->logfile($ordernum."|".$params['body']['bookOrderId'].'|100',"cancel_success");
			$response = array('code'=>200, 'describe'=>'success', 'partnerId'=>$params['partnerId'], 
				'body'=> array(
						'bookOrderId'=>$params['body']['bookOrderId'], 'partnerOrderId'=>$ordernum, 'orderStatus'=>6, 'autoRefund'=>1, 
						'refundDes'=>'退款成功', 'refundType'=>0, 'refundPrice'=>$params['body']['refundPrice'], 
						'refundRefactorage'=>0
				)
			);
			
			//这里需要执行退款通知
			file_get_contents("http://10.160.4.140/new/d/meituan/MT_refundnotice.php?ordern=".$ordernum."&partnerId=".$params['partnerId']);
		}
		else {
			$this->logfile($ordernum."|".$params['body']['bookOrderId'].'|'.$rs,"cancel_fail");
			exit('{"code":300,"describe":"订单取消失败","partnerId":"'.$params['partnerId'].'"}');
		}	
		
		exit(json_encode($response));
	}
	
	//通知
	public function RefundNotice($refundnotice,$url){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_POST, 1); 
		curl_setopt($ch, CURLOPT_HEADER, 0); 
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_URL,$url); 
		curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($refundnotice)); 
		curl_exec($ch);
		curl_close($ch);
	}
	
	// 查询订单
	public function PFT_Order_Query($params){		
		$ordernum = $params['body']['partnerOrderId'];
		$simxml = $this->inside->Order_Globle_Search("","","","","","","","","","","","",$ordernum,"","","","","",1,1,0,1,0,0,"",0,"","","","","");
		$simxml = simplexml_load_string($simxml);
		if((string)$simxml->Rec->UUordernum != $ordernum) 
			exit('{"code":300,"describe":"订单不存在","partnerId":"'.$params['partnerId'].'"}');
		if((string)$simxml->Rec->UUvcode!=0 && (int)$simxml->Rec->UUaid==298){ //青岛的门票 
			$QD = new QD_underW_World();
			$qd_orderstatus = $QD->GetAllOrderStatus((string)$simxml->Rec->UUvcode);
			$Status = $qd_orderstatus[0]['OrderStatus'];
			if($Status == 'S') $orderStatus = 0;
			elseif($Status == 'O'){
				if((int)$simxml->Rec->UUstatus == 0){
					$PFT_infunction = new AllFunction();
					$terminal = $PFT_infunction->Compatible_Check_IN((string)$simxml->Rec->UUsalerid,(string)$simxml->Rec->UUcode,date('Y-m-d H:i:s'));
					if($terminal  == 100) 
						$this->logfile((string)$simxml->Rec->UUordernum.'|'.$terminal,"QD_terminal_success");
					else $this->logfile((string)$simxml->Rec->UUordernum.'|'.$terminal,"QD_terminal_fail");
				}
				$orderStatus = 1;
			}
			elseif($Status == 'A') $orderStatus = 3;
		}
		else $orderStatus = (int)$simxml->Rec->UUstatus;// 0未使用|1已使用|2已过期|3被取消|4凭证码被替代|5被终端修改|6被终端撤销|7部分使用
		$reStatus = 0;
		if($orderStatus==0) $reStatus = 4;// 未使用对应支付成功
		if($orderStatus==1) $reStatus = 8;// 已全部使用 解释：usedQuantity ＋ refundQuantity = orderQuantity 即8状态
		if($orderStatus==3) $reStatus = 6;// 退款成功
		if($orderStatus==2) $reStatus = 9;// 没有对应
		
		$totalnum = $nownum = (int)$simxml->Rec->UUtnum;
		$refundnum = $usenum = 0;
		if((string)$simxml->Rec->UUconfirm_op!=0){// 修改过
			$sql = "select id,orderid,pre_num,done_num,rectime from pft_order_num_modify where orderid=$ordernum order by id asc limit 1";
			$GLOBALS['le']->query($sql);
			if($GLOBALS['le']->fetch_assoc()){
				$totalnum = $GLOBALS['le']->f('pre_num');
				$refundnum = $totalnum - $nownum;
				if($orderStatus==3)	$refundnum = $totalnum;
			}
		}		
		if($orderStatus==1) $usenum = $nownum;// 已使用票数
		$response = array('code'=>200, 'describe'=>'success', 'partnerId'=>$params['partnerId'],
			'body'=>array('bookOrderId'=>$params['body']['bookOrderId'], 'partnerOrderId'=>$ordernum, 'orderStatus'=>$reStatus,
					'orderQuantity'=>$totalnum, 'usedQuantity'=>$usenum, 'refundQuantity'=>$refundnum)
		);
		// print_r($response);
		exit(json_encode($response));
	}
	
	//拉取产品价格
	public function PFT_Get_Price($params){
		$startTime = strtotime($params['body']['startTime']); //开始时间
		$endTime = strtotime($params['body']['endTime']); //结束时间	
		$tids =  explode("|",$params['body']['partnerDealId']);
		$aid = $tids[0];
		$lid = $tids[1];
		$tid = $tids[2];
		$selmarketPrice = "select t.tprice,t.pid,t.ddays,f.dhour from uu_jq_ticket as t,uu_land_f as f where t.id=f.tid and t.id=$tid limit 1";
		$GLOBALS['le']->query($selmarketPrice);

		$p_info = $GLOBALS['le']->fetch_assoc();
		$marketPrice = $p_info['tprice'];  //门市价
		$pid = $p_info['pid'];   //产品ID
		$ddays = $p_info['ddays'] * 24; //提前预定天数/按小时算
		$dhour = ($p_info['dhour']==23) ? 1 : 24-$p_info['dhour']; //提前预定时间
		$aheadHour = $ddays + $dhour; 
		
		$sellist = "select pids FROM pft_product_sale_list WHERE fid={$this->mt_mid} AND aid={$aid} LIMIT 1";
		$GLOBALS['le']->query($sellist);
		$row = $GLOBALS['le']->fetch_assoc();
		if ( $row && $row['pids']!='A' ) 
		{
			if(!in_array($pid, explode(',', $row['pids']))){
				$sql = "SELECT id FROM pft_p_apply_evolute WHERE sid={$aid} AND fid={$this->mt_mid} LIMIT 1";
				$GLOBALS['le']->query($sql);
				if (!$GLOBALS['le']->fetch_assoc()) {
					exit('{"code":300,"describe":"无此转分销价格","partnerId":"'.$params['partnerId'].'"}');
				}
			}
		} 
		else {
			exit('{"code":300,"describe":"无此分销价格","partnerId":"'.$params['partnerId'].'"}');
		}	
		$bodys = array();
		for($i=$startTime;$i<=$endTime;$i+=86400){
			$get_lprice = $this->inside->Dynamic_Price_And_Storage('505270',$pid,date('Y-m-d',$i),1,1,1,$aid);
			if($get_lprice==105 || $get_lprice==1065) continue;
			$get_lprice_xml = simplexml_load_string($get_lprice);
			$lprice = (string)$get_lprice_xml->Rec->UUsprice;
			$stock = ((string)$get_lprice_xml->Rec->UUstorage == -1)? 100000000 : (string)$get_lprice_xml->Rec->UUstorage;
			//封装价格
            $body= array(
				'partnerDealId'=>$params['body']['partnerDealId'],
				'priceDate'=>date('Y-m-d',$i),
				'sellPrice'=>$lprice / 100 ,
				'marketPrice'=>$marketPrice,
				'stock'=>$stock,
				'aheadHour'=>$aheadHour,
			);
			$bodys[] = $body;  
		}
		$response  = array(
			'code' => 200,
			'describe' => 'success',
			'partnerId' => $params['partnerId'],
			'partnerDealId' =>$params['body']['partnerDealId'],
			'partnerPoiId' =>$params['body']['partnerPoiId'],
			'body' => $bodys
		);
		// print_r($response);
		$this->logfile(json_encode($response),"priceres");
		exit(json_encode($response));
	}
	
	private function response_header($partnerId,$totalSize){
		return array(
			'code' => 200,
			'describe' => 'success',
			'partnerId' => $partnerId,
			'totalSize' => $totalSize,
			'nextIncrementId' => '0',
			'body' => array()
		);
	}
	private function response_format_data($partnerId,$product,$k,$aid){
		$pic = strpos($product['imgpath'], "images.12301.cc/");
		if($pic !== false)	$urls = array($product['imgpath'],);  
		else	$urls = array('http://www.12301.cc/'.$product['imgpath'],);
		$imageTextNote = strip_tags(htmlspecialchars_decode($product['bhjq']),'<img>');
		$return = array(
			'partnerId' => $partnerId,
			'partnerSupplierId' => $aid,
			'partnerDealId' => $k,
			'partnerPoiId' => $product['landid'],
			'name' => $product['ltitle'].$product['ttitle'],
			'minimum' => $product['buy_limit_low'],
			'maximum' => ($product['buy_limit_up']==0)?99999:$product['buy_limit_up'],
			'marketPrice' => $product['tprice'],
			'sellPrice' => $product['ls'],
			'stock' => $product['stock'],
			'commissionRatio' => 0,//'佣金比例',
			'purchaseNote' => $product['jqts'],//'购票须知',
			'purchaseNote' => array(
				'chargeIncludeNote'=>'包含'.$product['ttitle'].'1张',
				'refundNote'=>'未在验证终端验证或窗口取纸质票的可进行在线退款，一经终端验证或取纸质票不可退。',
				'useNote'=>$product['getaddr'],
				'importantNote'=>$product['jqts'],
				'imageTextNote'=>$imageTextNote
			), 
			'needBook' => ($product['ddays'] == 0)?0:1, // 是否需要预约
			'aheadHour' => $product['dhour'], // 提前预定时间 0 本天的都可以预定 1  本天23小时之前 25 前一天23小时
			'canRefund' => 1, // 受否支持退款 是 0:不可退；1：可退
			'refundRatio' => 0,// 退款比例
			'startTime' => '2012-12-11 00:00:00',// 上架时间
			'endTime' => '2016-12-31 23:59:59', //下架时间
			'pics' => array(
				'urls' =>$urls,
			),
			'visitorRequire' => array(
				'firstVisitor' => array(
					'name' => true, // 取票人是否必须
					'pinyin' => false, // 姓名拼音是否必须
					'mobile' => true, // 手机号是否必须
					'address' => false,// 地址是否必须
					'postCode' => false,// 邮编是否必须
					'credentials' =>($product['tourist_info'] == 1)?true:false,// 证件是否必须
				),
				'otherVisitor' => array(
					'name' => false, // 取票人是否必须
					'pinyin' => false, // 姓名拼音是否必须
					'mobile' => false, // 手机号是否必须
					'address' => false,// 地址是否必须
					'postCode' => false,// 邮编是否必须
					'credentials' => false,// 证件是否必须
				),
			),
		);
		if($product['tourist_info'] == 1)  
			$return['visitorRequire']['firstVisitor']['credentialsType'] = (object)array("0"=>"身份证","1"=>"护照","2"=>"军官证","3"=>"台胞证","4"=>"港澳证");
		return $return;
	}

	
	//重发短信
	public function ResendCode($params){
		$pft_order =  $params['body']['partnerOrderId'];		
		$resend = $this->outside->__soapCall("reSend_SMS_Global_PL",array("ac"=>'505270',"pw"=>'54a3fdb31cad4ef63cac2d9cc82cf784',"in0"=>$pft_order));
		$resend_xml = simplexml_load_string($resend);
		$UUdone = (int)$resend_xml->Rec->UUdone;
		if($UUdone == 100){
			$seecode = $this->outside->__soapCall("Terminal_Code_Verify",array("ac"=>'505270',"pw"=>'54a3fdb31cad4ef63cac2d9cc82cf784',"in0"=>$pft_order));
			$seecode_xml = simplexml_load_string($seecode);
			$code = (string)$seecode_xml->Rec->UUcode;
			$response = array(
				'code' => 200,
				'describe' => '重发成功',
				'partnerId' => $params['partnerId'],
				'body'=>array(
					'voucherType'=>0,
					'voucher'=>$code
				)
			);
		}else{
			$response = array(
				'code' => 300,
				'describe' => (int)$resend_xml->Rec->UUerrorcode,
				'partnerId' => $params['partnerId'],
				'body'=>array(
					'voucherType'=>0,
					'voucher'=>''
				)
			);
		}
		exit(json_encode($response));
	}
	
	// public function logfile($txt,$path){
		// $fp = fopen('/var/www/html/new/d/logs/api/meituan/'.$path.date('Y-m-d').'.txt',"a");
		// flock($fp, LOCK_EX) ;
		// fwrite($fp,date('Y-m-d H:i:s').'|'.$txt."\n");
		// flock($fp, LOCK_UN);
		// fclose($fp);
	// }
	
	public function logfile($word,$path){
		$filepath= '/var/www/html/new/d/logs/api/meituan/'.$path.'.txt';
		if(file_exists($filepath)){
			$word = date("Y-m-d H:i:s")."|".$word;
			// $word = mb_convert_encoding($word, 'GBK', 'UTF-8');
			$maxsize  = 1024*1024*10;
			$filesize = filesize($filepath);
			$filetype = end(explode(".",$filepath));
			$filename = substr($filepath,0,strpos($filepath,'.'));
			if($filesize>$maxsize)
			{
				rename($filepath, $filename.'_'.date('YmdHis').'.'.$filetype);
				$handler=fopen($filepath,'w');
				flock($handler, LOCK_EX) ;
				fwrite($handler,"\n".$word);
				flock($handler, LOCK_UN);
				fclose($handler);
			}
			else
			{
				$fp = fopen('/var/www/html/new/d/logs/api/meituan/'.$path.'.txt',"a");
				flock($fp, LOCK_EX);
				fwrite($fp,$word."\n");
				flock($fp, LOCK_UN);
				fclose($fp);
			}
		}else{
			$fp = fopen('/var/www/html/new/d/logs/api/meituan/'.$path.'.txt',"a");
			flock($fp, LOCK_EX);
			fwrite($fp,date('Y-m-d H:i:s')."|".$word."\n");
			flock($fp, LOCK_UN);
			fclose($fp);
		}
	}
	
	
}


// array(
	// 'code' => 200,
	// 'describe' => 'success',
	// 'partnerId' => '合作方ID',
	// 'totalSize' => '',
	// 'nextIncrementId' => '下次增量查询的id',
	// 'body' => array(
		// 'partnerId' => '合作方ID',
		// 'partnerSupplierId' => '商家ID',
		// 'partnerDealId' => '产品ID',
		// 'partnerPoiId' => '产品景点ID',
		// 'name' => '景区+门票名称',
		// 'pics' => array(
			// 'urls' =>  '产品图片',
		// ),
		// 'visitorRequire' => array(
			// 'firstVisitor' => array(
				// 'name' => true, // 取票人是否必须
				// 'pinyin' => false, // 姓名拼音是否必须
				// 'mobile' => true, // 手机号是否必须
				// 'address' => false,// 地址是否必须
				// 'postCode' => false,// 邮编是否必须
				// 'credentials' => false,// 证件是否必须
				// 'credentialsType' => array('身份证'),
			// ),
			// 'otherVisitor' => array(
				// 'name' => false, // 取票人是否必须
				// 'pinyin' => false, // 姓名拼音是否必须
				// 'mobile' => false, // 手机号是否必须
				// 'address' => false,// 地址是否必须
				// 'postCode' => false,// 邮编是否必须
				// 'credentials' => false,// 证件是否必须
				// 'credentialsType' => array('身份证'),
			// ),
		// ),
		// 'minimum' => '每个订单最少购买数量限制',
		// 'maximum' => '每个订单最多购买数量限制',
		// 'marketPrice' => '市场价',
		// 'sellPrice' => '销售价',
		// 'stock' => '库存',
		// 'commissionRatio' => '佣金比例',
		// 'purchaseNote' => '购票须知',
		// 'needBook' => false, // 是否需要预约
		// 'aheadHour' => 0, // 提前预定时间 0 本天的都可以预定 1  本天23小时之前 25 前一天23小时
		// 'canRefund' => 0, // 受否支持退款 是 0:不可退；1：可退
		// 'refundRatio' => 0,// 退款比例
		// 'startTime' => '2012-12-11 00:00:00',// 上架时间
		// 'endTime' => '下架时间',
	// ),
// );
